package com.echo.register.msm.api;

import com.echo.register.common.result.Result;
import com.echo.register.msm.service.MsmService;
import com.echo.register.msm.utils.RandomUtil;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName: MsmApicontroller
 * @Package: com.echo.register.msm.api
 * @Description:
 * @Author 谢同学
 * @Create 2023/12/30 15:50
 * @Version 1.0
 */
@RestController
@Api(tags = "短信服务接口")
@RequestMapping("/api/msm")
public class MsmApiController {
    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //发送手机验证码
    @GetMapping("/send/{phone}")
    public Result sendCode(@PathVariable String phone) {
        //先从Redis查询 判断验证码是否已经发过 并且没有失效
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return Result.ok();
        }
        // 如果验证码没发过或者已经失效
        // 设置验明证
        code = RandomUtil.getSixBitRandom();
        if (msmService.send(phone,code)) {
            // 发送成功，存入缓存，设置过期时间
            redisTemplate.opsForValue().set(phone,code,10, TimeUnit.MINUTES);
            return Result.ok();
        }else {
            return Result.fail().message("验证码发送失败");
        }
    }
}
